package com.qingyun.customview.autosearch

import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.Runnable

class AutoSearchHandler(
    private val debounceTime: Long = 500,
    private val minQueryLength: Int = 2,
    private val onSearch: (query: String) -> Unit,
) {
    private val handler = Handler(Looper.getMainLooper())
    private var searchRunnable: Runnable? = null

    fun onQueryChanged(query: String?) {
        searchRunnable?.let {
            handler.removeCallbacks(it)
        }
        val trimmedQuery = query?.trim() ?: ""
        if (trimmedQuery.length < minQueryLength) {
            return
        }

        searchRunnable = Runnable {
            onSearch.invoke(trimmedQuery)
        }.also {
            handler.postDelayed(it, debounceTime)
        }
    }

    /**
     * 主动触发搜索（立即执行，忽略防抖）
     */
    fun triggerSearchImmediately(query: String?) {
        handler.removeCallbacksAndMessages(null)
        onQueryChanged(query)
    }

    fun clear() {
        handler.removeCallbacksAndMessages(null)
        searchRunnable = null
    }
}